
if ( typeof Skt.Groups === 'undefined' )
	Skt.Groups = {};


Skt.Groups.setup = function(sketchpad) {
	sketchpad.on("groupsUpdated", Skt.Groups.handleGroupsUpdated, Skt.Groups);
	sketchpad.on("groupUpdate", Skt.Groups.handleGroupUpdate, Skt.Groups);
	sketchpad.on("groupsManagerInvitationUpdate", Skt.Groups.handleGroupsManagerInvitationUpdate, Skt.Groups);
	
	Skt.Groups.updateGroupsRoomlists(sketchpad);
	Skt.Groups.setupDragAndDropStudents(sketchpad);
};

Skt.Groups.handleAcceptInvitation = function(invitedId, groupId) {
	var group = Skt.sketchpad.getGroupsManager().findGroup(groupId);
	
	if ( group == null ) {
		console.log("[warning] Skt.Groups.handleAcceptInvitation group not found, id: " + params.groupId);
		return;
	}
	
	group.addMember(invitedId);
};

Skt.Groups.handleGroupsManagerInvitationUpdate = function(params) {
	var user = Skt.sketchpad.getUser();
	var inviter = Skt.sketchpad.getUsersManager().getUser(params.inviterId);
	var group = Skt.sketchpad.getGroupsManager().findGroup(params.groupId);
	
	if ( group == null ) {
		console.log("[warning] Skt.Groups.handleGroupsManagerInvitationUpdate group not found, id: " + params.groupId);
		return;
	}
	
	if ( params.type == Skt.InvitationType.ISSUED ) {
		if ( user.id == params.invitedId && !group.isMember(user.id) ) {
			Skt.Util.addNotification(inviter.name + ' has invited you to join his notes group "' + group.getName() + '"', 
					'Skt.Groups.handleAcceptInvitation(' + params.invitedId + ',' + group.getId() + ')',
					';');
		}
	} else {
		
	}
	
};

Skt.Groups.handleGroupUpdate = function(params) {
	setTimeout(function(){
		Skt.UsersSidebar.updateGroups(Skt.sketchpad);
		Skt.Groups.updateGroupsRoomlists(Skt.sketchpad);	
	}, 100);
};

Skt.Groups.handleGroupsUpdated = function(params) {
	setTimeout(function(){
		Skt.Groups.updateGroupsRoomlists(Skt.sketchpad);
	}, 100);
};

Skt.Groups.handleStudentDroppedOnGroup = function(studentId, groupId) {
	var usersManager = Skt.sketchpad.getUsersManager();
	var groupsManager = Skt.sketchpad.getGroupsManager();
	var student = usersManager.getUser(Number(studentId));
	var group = groupsManager.findGroup(Number(groupId));
	var user = Skt.sketchpad.getUser();
	
	if ( student == null ) {
		console.log("[error] Skt.Groups.handleStudentDroppedOnGroup can't find user with id: " + studentId);
		return;
	}
	
	if ( group == null ) {
		console.log("[error] Skt.Groups.handleStudentDroppedOnGroup can't find group with id: " + groupId);
		return;
	}
	
	if ( !group.isMember(student.id) ) {
		if ( group.getType() == Skt.GroupType.WORK ) {
			if ( user.type == Skt.UserType.TEACHER )
				group.addMember(student.id);
			else
				alert("You don't have permission to add members to work groups");
		} else {
			if ( group.isMember(user.id) ) {
				groupsManager.issueInvitation(group.getId(), user.id, student.id);
				Skt.Groups.showInvitationSentNotification(group.getId(), student.id);
			} else {
				alert("You can't invite people to this group because you're not a member");
			}
		}
	} else {
		alert("The user you're trying to invite is already in the group");
	}
	
};

Skt.Groups.showInvitationSentNotification = function(groupId, studentId) {
	var usersManager = Skt.sketchpad.getUsersManager();
	var groupsManager = Skt.sketchpad.getGroupsManager();
	var student = usersManager.getUser(Number(studentId));
	var group = groupsManager.findGroup(Number(groupId));
	
	if ( student == null ) {
		console.log("[error] Skt.Groups.showInvitationSentNotification can't find user with id: " + studentId);
		return;
	}
	
	if ( group == null ) {
		console.log("[error] Skt.Groups.showInvitationSentNotification can't find group with id: " + groupId);
		return;
	}
	
	Skt.Util.addNotification('An invitation has been sent to ' + student.name + ' to join your group "' + group.getName() + '".');
};

Skt.Groups.setupDragStudents = function(sketchpad) {
	$(".student-li").draggable({
		appendTo : "body",
		helper : "clone",
		revert : "invalid",
		zIndex : 1000,
		start : function(e, ui) {
			$(ui.helper).addClass("dragged-student-li");
		},
		stop: function(e, ui) {}
	});
};

Skt.Groups.setupDropStudents = function(sketchpad) {
	$('.group').droppable({
		hoverClass : "group-hover",
		accept: '.student-li',
		drop : function(event, ui) {
			var userId = Number(ui.draggable[0].dataset.id);
			var groupId = Number(this.dataset.id);
			Skt.Groups.handleStudentDroppedOnGroup(userId, groupId);
		}
	});
};

Skt.Groups.setupDragAndDropStudents = function(sketchpad) {
	Skt.Groups.setupDragStudents(sketchpad);
	Skt.Groups.setupDropStudents(sketchpad);
};

Skt.Groups.updateGroupsRoomlists = function(sketchpad) {
	var user = sketchpad.getUser();
	var groupsManager = sketchpad.getGroupsManager();
	var workGroups = groupsManager.getWorkGroups();
	var notesGroups = groupsManager.getNoteGroups();
	
	if ( workGroups.length <= 0 && notesGroups.length <= 0 ) {
		$("#groups-list").html("There are no groups created");
	} else {
		var html = "";
		
		for ( var i = 0; i < workGroups.length; ++i ) {
			if ( workGroups[i].isMember(user.id) )
				html += Skt.Groups.buildGroupRoomlistContainerHtml(workGroups[i]);
		}
		
		for ( var i = 0; i < notesGroups.length; ++i ) {
			if ( notesGroups[i].isMember(user.id) )
				html += Skt.Groups.buildGroupRoomlistContainerHtml(notesGroups[i]);
		}
		
		$("#groups-list").html(html);
		
		for ( var i = 0; i < workGroups.length; ++i ) {
			if ( workGroups[i].isMember(user.id) )
				Skt.SlidesSidebar.updateAllCanvasesFromRoomlist(workGroups[i].getRoomList());
		}
			
		for ( var i = 0; i < notesGroups.length; ++i ) {
			if ( notesGroups[i].isMember(user.id) )
				Skt.SlidesSidebar.updateAllCanvasesFromRoomlist(notesGroups[i].getRoomList());
		}
		
		Skt.Slide.updateSelectedCanvas();
		Skt.Util.updateEmptyMessage(sketchpad);
	}
};

Skt.Groups.buildGroupRoomlistContainerHtml = function(group) {
	var res = '';
	
	res += '<div id="group-slides-container-' + group.getId();
	res += '" class="group-slides-container">';
	
		res += '<div id="group-slides-container-header-' + group.getId(); 
		res += '" class="group-slides-container-header">';
		
			res += '<span class="group-slides-container-header-toggler"'; 
			res += ' onclick="Skt.Groups.handleGroupTogglerClick(' + group.getId();
			res += ')">';
			
				res += '<span class="triangle-toggle-icon ui-icon ui-icon-triangle-1-s"></span>';
				
				res += '<span class="group-type-icon ui-icon ';
				if ( group.getType() == Skt.GroupType.WORK )
					res += 'ui-icon-star';
				else
					res += 'ui-icon-note';
				res += '"></span>';
				
				res += '<span class="group-slides-container-group-name">' + group.getName() + '</span>';
			
			res += '</span>';
			
			res += '<i class="group-add-slide-button btn btn-mini icon-plus"'; 
			res += ' onclick="Skt.Util.postRoomCreation(Skt.sketchpad, Skt.SlideType.GROUP, ' + group.getId() + ');"></i>';
		
		res += '</div>';
		
		res += '<div id="group-slides-container-body-' + group.getId(); 
		res += '" class="group-slides-container-body">';

			res += '<div id="room-list-group-' + group.getId();
			res += '" class="room-list">';
			
				res += '<ul id="rooms-group-' + group.getId();
				res += '" class="rooms-ul nav nav-pills"></ul>';
			
			res += '</div>';
		
		res += "</div>";
	
	res += '</div>';
	
	return res;
};

Skt.Groups.handleGroupTogglerClick = function(groupId) {
	$("#group-slides-container-body-" + groupId).slideToggle();
};

